' Copyright (c) 2006, Tom van de Kerkhof (Blog: http://blogs.jpworks.be/Tom)
' All rights reserved.
' Redistribution and use in source and binary forms, with or without
' modification, are permitted provided that the following conditions are met:
'
'     * Redistributions of source code must retain the above copyright
'       notice, this list of conditions and the following disclaimer.
'     * Redistributions in binary form must reproduce the above copyright
'       notice, this list of conditions and the following disclaimer in the
'       documentation and/or other materials provided with the distribution.
'     * The name of Tom van de Kerkhof may not be used to endorse or promote products
'       derived from this software without specific prior written permission.
'
' THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY
' EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
' WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL MARK BRACEWELL BE LIABLE FOR ANY
' DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
' (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
' LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
' ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
' (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
' SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports ClubStarterKit.Data
Imports SubSonic
Imports ClubStarterKit.Web.Controls

Namespace ClubStarterKit.Web.Controls
    Public Class PollControl
        Inherits WebControl
        Implements INamingContainer
        Private _question As PollQuestion
        Public Property Question() As PollQuestion
            Get
                If _question Is Nothing Then
                    _question = CType(ViewState("Question"), PollQuestion)
                End If
                Return _question
            End Get
            Set(ByVal Value As PollQuestion)
                ViewState("Question") = Value
            End Set
        End Property

        Public ReadOnly Property AnswerTable() As PollAnswersCollection
            Get
                Return LoadAnswers()
            End Get
        End Property
        Public ReadOnly Property IsUserAllowedToVote() As Boolean
            Get
                If Not Page.User.Identity.IsAuthenticated Then
                    Return False
                End If
                If Poll.CheckUserAlreadyVoted(Question.PollId, New Guid(Membership.GetUser().ProviderUserKey.ToString())) Then
                    Return False
                End If
                Return True
            End Get
        End Property

        Private _selectedPollId As Guid

        Public Property SelectedPollId() As Guid
            Get
                Return _selectedPollId
            End Get
            Set(ByVal Value As Guid)
                _selectedPollId = Value
            End Set
        End Property


        Private Sub LoadQuestion()
            If _selectedPollId = Guid.Empty Then
                Question = Poll.GetLatestQuestion()
            Else
                Question = Poll.LoadQuestion(_selectedPollId)
            End If
        End Sub

        Private Function LoadAnswers() As PollAnswersCollection
            Return Poll.GetAnswersForPollQuestion(Question.PollId)
        End Function

        Private Function HasUserAlreadyVoted() As Boolean
            Return Poll.CheckUserAlreadyVoted(Question.PollId, New Guid(Membership.GetUser().ProviderUserKey.ToString()))
        End Function

        Protected Overrides Sub OnLoad(ByVal e As EventArgs)
            If Not Page.IsPostBack Then
                LoadQuestion()
            End If
        End Sub

        Protected Overrides Sub CreateChildControls()
            MyBase.CreateChildControls()
            CreateControls()
        End Sub

        Private Sub CreateControls()
            If Question Is Nothing Then
                Dim noPollAvailableLabel As New Label()
                noPollAvailableLabel.Text = "No poll available"
                Me.Controls.Add(New LiteralControl("<i>"))
                Me.Controls.Add(noPollAvailableLabel)
                Me.Controls.Add(New LiteralControl("</i>"))
            Else

            End If
            'Hyperlink
            Dim hyp As New HyperLink()
            hyp.NavigateUrl = "~/poll/List.aspx"
            hyp.Text = "All polls"

            Me.Controls.Add(hyp)
            Me.Controls.Add(New LiteralControl("<br/>"))
            Me.Controls.Add(New LiteralControl("<br/>"))

            'Question
            Dim questionLabel As New Label()
            questionLabel.Text = Question.Question
            questionLabel.Style.Add(HtmlTextWriterStyle.FontWeight, "bold")
            Me.Controls.Add(questionLabel)

            Me.Controls.Add(New LiteralControl("<br/>"))

            'Me.Controls.Add(New LiteralControl("<ul>"))

            If IsUserAllowedToVote Then

                Dim rbl As New RadioButtonList()
                'The LinkButton Answers
                Dim answer As PollAnswers
                If Not AnswerTable Is Nothing Then
                    For Each answer In AnswerTable
                        rbl.Items.Add(New ListItem(answer.Answer, answer.PollAnswerId.ToString()))
                    Next
                End If

                Me.Controls.Add(rbl)
                Me.Controls.Add(New LiteralControl("<br />"))

                'only render the SubmitButton when there are answers
                If Not AnswerTable Is Nothing Then
                    If AnswerTable.Count > 0 Then
                        Dim rlb As New RolloverButton()
                        rlb.Text = "Submit"
                        AddHandler rlb.Click, AddressOf SubmitButton_Click

                        Me.Controls.Add(rlb)
                    End If
                End If

                Me.Controls.Add(New LiteralControl("<br />"))


            Else
                Me.Controls.Add(New LiteralControl("<ul>"))
                'The Label answers
                Dim row As PollAnswers
                If Not AnswerTable Is Nothing Then

                    For Each row In AnswerTable
                        Dim percentage As Decimal = ComputePercentage(Poll.NumberOfVotesByAnswer(row.PollAnswerId))

                        Me.Controls.Add(New LiteralControl("<li>"))

                        Dim answerLabel As Label = New Label()
                        answerLabel.Text = String.Format("{0}:", row.Answer)
                        Me.Controls.Add(answerLabel)

                        Me.Controls.Add(New LiteralControl("<br/>"))

                        Dim img As New System.Web.UI.WebControls.Image
                        img.ImageUrl = "~/images/pixel.png"
                        img.Height = New Unit(7)
                        img.Width = New Unit(percentage.ToString())
                        Me.Controls.Add(img)

                        Dim percentageLabel As Label = New Label()
                        percentageLabel.Text = String.Format(" ({0}%)", percentage.ToString())
                        Me.Controls.Add(percentageLabel)

                        Me.Controls.Add(New LiteralControl("</li>"))
                    Next
                End If

                Me.Controls.Add(New LiteralControl("</ul>"))


                'The summary
                Dim summaryLink As New HyperLink
                Dim ttlvotes As String = Poll.CountTotalVotes(Question.PollId).ToString()
                If ttlvotes = "1" Then
                    summaryLink.Text = String.Format("{0} vote", ttlvotes)
                Else
                    summaryLink.Text = String.Format("{0} votes", ttlvotes)
                End If

                summaryLink.NavigateUrl = "~/poll/View.aspx?PollId=" + Question.PollId.ToString()
                Me.Controls.Add(summaryLink)

                Me.Controls.Add(New LiteralControl("<br/>"))

                Dim totalReactionsLink As HyperLink = New HyperLink()
                Dim ttlrxns As String = Poll.CountTotalReactions(Question.PollId).ToString()
                If ttlrxns = "1" Then
                    totalReactionsLink.Text = String.Format("{0} reactie", ttlrxns)
                Else
                    totalReactionsLink.Text = String.Format("{0} reacties", ttlrxns)
                End If

                totalReactionsLink.NavigateUrl = "~/poll/View.aspx?PollId=" + Question.PollId.ToString()
                Me.Controls.Add(totalReactionsLink)
            End If

            'Administrator section
            If Page.User.IsInRole("Administrators") Then
                Me.Controls.Add(New LiteralControl("<br/>"))
                Me.Controls.Add(New LiteralControl("<br/>"))
                Dim adminLinkButton As New RolloverButton
                adminLinkButton.PostBackUrl = "~/poll/Manage.aspx"
                adminLinkButton.Text = "Manage Polls"
                Me.Controls.Add(adminLinkButton)
            End If
        End Sub
        Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            If Not (CType(Me.Controls(5), RadioButtonList)).SelectedValue Is Nothing Then
                Poll.Vote(Question.PollId, New Guid((CType(Me.Controls(5), RadioButtonList)).SelectedValue), New Guid(Membership.GetUser().ProviderUserKey.ToString()))

                Me.Controls.Clear()
                LoadAnswers()
                CreateControls()
            End If
        End Sub


        Private Function ComputePercentage(ByVal numberOfVotes As Decimal) As Decimal
            Dim percentage As Decimal = 0
            Dim totalVotes As Integer = Poll.CountTotalVotes(_question.PollId)
            If totalVotes > 0 Then
                percentage = System.Math.Round((numberOfVotes / totalVotes) * 100, 0)
            End If
            Return percentage
        End Function

    End Class
End Namespace
